package com.example.xjt.safe;

import cn.hutool.core.collection.CollectionUtil;
import com.example.xjt.orm.role.RoleRepo;
import com.example.xjt.orm.ur.UserRole;
import com.example.xjt.orm.ur.UserRoleRepo;
import com.example.xjt.orm.user.UserDO;
import com.example.xjt.orm.user.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SafePrincipalService implements UserDetailsService {

    @Autowired
    private UserRepo userRepo;
    @Autowired
    private RoleRepo roleRepo;
    @Autowired
    private UserRoleRepo userRoleRepo;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO u = userRepo.findByAccount(username);
        if (u == null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        SafePrincipal safePrincipal = new SafePrincipal();
        safePrincipal.setUsername(u.getAccount());
        safePrincipal.setPassword(u.getPwd());
        safePrincipal.setUid(u.getId());

        safePrincipal.setEnabled(Boolean.TRUE);

        List<UserRole> userRoleSet = userRoleRepo.findAllByUid(safePrincipal.getUid());
        if (CollectionUtil.isNotEmpty(userRoleSet)) {
            List<Long> ridList = userRoleSet.stream().map(UserRole::getRid).distinct().collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(ridList)) {
                safePrincipal.setRoleList(roleRepo.findAllById(ridList));
            }
        }


        return safePrincipal;
    }
}
